<?php
/**                                          
 * 模版
 * @author M2
 * @version 1.0
 * create Date 2013-04-27
 */
class TemplateModel extends Model {
	/**
	 * 解析模板（将模板中变量替换成数据）
	 * @param string  $tpl_name    模板名称
	 * @param array   $data        模板中的变量和数据
	 * @param boolean $auto_record 是否添加模板记录
	 * @return boolean|string 模板解析的结果
	 */
	public function parseTemplate($tpl_name, $data, $auto_record = null) {
		$map['name'] = $tpl_name;
		$template	 = $this->where($map)->find();
		if (!$template) return false;
		$auto_record	= isset($auto_record) ? $auto_record : $template['is_cache'];
		$title			= '';
		$body			= '';
		//标题模板
		if ( !empty($template['title']) ) {
			$keys	= array_keys($data['title']);
			$values	= array_values($data['title']);
			foreach($keys as $k => $v) $keys[$k] = '{'.$v.'}';
			$template['title'] = str_replace($keys, $values, $template['title']);
			unset($keys, $values);
		}
		//内容模板
		if ( !empty($template['body']) ) {
			$keys	= array_keys($data['body']);
			$values	= array_values($data['body']);
			foreach($keys as $k => $v) $keys[$k] = '{'.$v.'}';
			$template['body'] = str_replace($keys, $values, $template['body']);
			unset($keys, $values);
		}
		//自动添加模板记录
		if ($auto_record) {
			$record_data['uid']			= isset($data['uid']) ? $data['uid'] : $_SESSION['mid'];
			$record_data['tpl_name']	= $template['name'];
			$record_data['tpl_alias']	= $template['alias'];
			$record_data['type']		= $template['type'];
			$record_data['type2']		= $template['type2'];
			$record_data['ctime']		= time();
			unset($template['tpl_id']);
			$record_data['data']		= serialize($template);
			return M('template_record')->add($record_data);
		}else {
			return $template;
		}
	}
}